<template>
  <el-dialog
      v-model="dialogVisible"
      title="选择升级分支"
      width="30%"
      :close-on-click-modal="false"
  >
    <el-select v-model="selectedBranch" placeholder="请选择分支" style="width: 100%">
      <el-option
          v-for="item in branchInfoList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
      />
    </el-select>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        {{ loading ? '升级中...' : '确认' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="deployDeplDockerInfoUpgradeDialog">
import {ref} from 'vue'
import {useMessage} from "/@/hooks/message";
import {listAllBranchInfo} from "/@/api/bms/deploy/branchInfo";
import {upgrade} from "/@/api/bms/deploy/dockerInfo";

const dialogVisible = ref(false)
const selectedBranch = ref('')
const dockerInfoId = ref('')
const branchInfoList = ref([])
const loading = ref(false)

const openDialog = (id) => {
  dockerInfoId.value = id
  loadBranchInfoList()
  dialogVisible.value = true
}

const loadBranchInfoList = async () => {
  const res = await listAllBranchInfo()
  branchInfoList.value = res.data
}

const emit = defineEmits(['refresh'])

const handleConfirm = async () => {
  if (!selectedBranch.value) {
    useMessage().warning('请选择分支')
    return
  }
  loading.value = true  // 开始 loading
  try {
    const params = {
      id: dockerInfoId.value,
      branchId: selectedBranch.value
    }
    await upgrade(params)
    useMessage().success('升级成功')
    dialogVisible.value = false
    emit('refresh')
  } catch (error) {
    console.error('升级失败:', error)
  } finally {
    loading.value = false  // 结束 loading
  }
}

defineExpose({
  openDialog
})
</script>
